using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;

namespace JGSY.CMS.LowCode.Platform.Domain.Entities
{
    /// <summary>
    /// 租户数据备份实体
    /// 用于管理租户数据的备份操作和记录
    /// </summary>
    [Table("tenant_data_backups")]
    public class TenantDataBackup : ITenantEntity
    {
        /// <summary>
        /// 主键ID
        /// </summary>
        [Key]
        public long Id { get; set; }

        /// <summary>
        /// 租户ID
        /// </summary>
        [Required]
        [StringLength(50)]
        public string TenantId { get; set; } = string.Empty;

        /// <summary>
        /// 备份名称
        /// </summary>
        [Required]
        [StringLength(200)]
        public string BackupName { get; set; } = string.Empty;

        /// <summary>
        /// 备份类型
        /// 如：full, incremental, differential
        /// </summary>
        [Required]
        [StringLength(50)]
        public string BackupType { get; set; } = string.Empty;

        /// <summary>
        /// 备份状态
        /// 如：pending, running, completed, failed
        /// </summary>
        [Required]
        [StringLength(50)]
        public string Status { get; set; } = "pending";

        /// <summary>
        /// 备份大小（字节）
        /// </summary>
        public long BackupSizeBytes { get; set; }

        /// <summary>
        /// 备份文件路径
        /// </summary>
        [StringLength(500)]
        public string? FilePath { get; set; }

        /// <summary>
        /// 存储位置
        /// 如：local, s3, azure等
        /// </summary>
        [StringLength(100)]
        public string StorageLocation { get; set; } = string.Empty;

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartedAt { get; set; } = DateTime.UtcNow;

        /// <summary>
        /// 完成时间
        /// </summary>
        public DateTime? CompletedAt { get; set; }

        /// <summary>
        /// 过期时间
        /// </summary>
        public DateTime? ExpiresAt { get; set; }

        /// <summary>
        /// 备份的数据表
        /// JSON数组格式存储表名列表
        /// </summary>
        [Column(TypeName = "text")]
        public string? BackupTables { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        [Column(TypeName = "text")]
        public string? ErrorMessage { get; set; }

        /// <summary>
        /// 触发方式
        /// 如：manual, scheduled, api
        /// </summary>
        [StringLength(50)]
        public string TriggerType { get; set; } = "manual";

        /// <summary>
        /// 操作用户ID
        /// </summary>
        public long? OperatorUserId { get; set; }

        /// <summary>
        /// 备份描述
        /// </summary>
        [StringLength(1000)]
        public string? Description { get; set; }

        /// <summary>
        /// 备份元数据
        /// JSON格式存储额外信息
        /// </summary>
        [Column(TypeName = "text")]
        public string? Metadata { get; set; }

        /// <summary>
        /// 文件MD5校验和
        /// 用于验证备份文件完整性
        /// </summary>
        [StringLength(100)]
        public string? ChecksumMD5 { get; set; }

        /// <summary>
        /// 文件SHA256校验和
        /// 用于验证备份文件完整性
        /// </summary>
        [StringLength(100)]
        public string? ChecksumSHA256 { get; set; }

        /// <summary>
        /// 关联备份策略ID
        /// </summary>
        [StringLength(100)]
        public string? BackupPolicyId { get; set; }

        /// <summary>
        /// 压缩前原始大小（字节）
        /// </summary>
        public long? OriginalSizeBytes { get; set; }

        /// <summary>
        /// 压缩比
        /// </summary>
        public decimal? CompressionRatio { get; set; }

        /// <summary>
        /// 是否加密存储
        /// </summary>
        public bool IsEncrypted { get; set; } = false;

        /// <summary>
        /// 加密算法
        /// 如：AES256, RSA等
        /// </summary>
        [StringLength(100)]
        public string? EncryptionAlgorithm { get; set; }

        /// <summary>
        /// 备份验证状态
        /// 如：pending, valid, invalid, skipped
        /// </summary>
        [StringLength(50)]
        public string ValidationStatus { get; set; } = "pending";

        /// <summary>
        /// 验证完成时间
        /// </summary>
        public DateTime? ValidatedAt { get; set; }

        // 计算属性

        /// <summary>
        /// 备份耗时（分钟）
        /// </summary>
        [NotMapped]
        public int? DurationMinutes => CompletedAt.HasValue ? 
            (int?)Math.Round((CompletedAt.Value - StartedAt).TotalMinutes) : null;

        /// <summary>
        /// 是否已过期
        /// </summary>
        [NotMapped]
        public bool IsExpired => ExpiresAt.HasValue && DateTime.UtcNow > ExpiresAt.Value;

        /// <summary>
        /// 备份大小（MB）
        /// </summary>
        [NotMapped]
        public decimal BackupSizeMB => Math.Round((decimal)BackupSizeBytes / (1024 * 1024), 2);

        /// <summary>
        /// 是否已验证完整性
        /// </summary>
        [NotMapped]
        public bool IsValidated => ValidationStatus == "valid";

        /// <summary>
        /// 压缩效率百分比
        /// </summary>
        [NotMapped]
        public decimal? CompressionEfficiency => OriginalSizeBytes > 0 && CompressionRatio.HasValue ? 
            Math.Round((1 - CompressionRatio.Value) * 100, 2) : null;
    }

    /// <summary>
    /// 租户数据迁移实体
    /// 用于管理租户数据的迁移操作
    /// </summary>
    [Table("tenant_data_migrations")]
    public class TenantDataMigration : ITenantEntity
    {
        /// <summary>
        /// 主键ID
        /// </summary>
        [Key]
        public long Id { get; set; }

        /// <summary>
        /// 源租户ID
        /// </summary>
        [Required]
        [StringLength(50)]
        public string TenantId { get; set; } = string.Empty;

        /// <summary>
        /// 目标租户ID
        /// </summary>
        [StringLength(50)]
        public string? TargetTenantId { get; set; }

        /// <summary>
        /// 迁移名称
        /// </summary>
        [Required]
        [StringLength(200)]
        public string MigrationName { get; set; } = string.Empty;

        /// <summary>
        /// 迁移类型
        /// 如：export, import, transfer, clone
        /// </summary>
        [Required]
        [StringLength(50)]
        public string MigrationType { get; set; } = string.Empty;

        /// <summary>
        /// 迁移状态
        /// 如：pending, running, completed, failed, cancelled
        /// </summary>
        [Required]
        [StringLength(50)]
        public string Status { get; set; } = "pending";

        /// <summary>
        /// 处理的记录数
        /// </summary>
        public long ProcessedRecords { get; set; }

        /// <summary>
        /// 总记录数
        /// </summary>
        public long TotalRecords { get; set; }

        /// <summary>
        /// 失败的记录数
        /// </summary>
        public long FailedRecords { get; set; }

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartedAt { get; set; } = DateTime.UtcNow;

        /// <summary>
        /// 完成时间
        /// </summary>
        public DateTime? CompletedAt { get; set; }

        /// <summary>
        /// 迁移的数据表
        /// JSON数组格式存储表名列表
        /// </summary>
        [Column(TypeName = "text")]
        public string? MigrationTables { get; set; }

        /// <summary>
        /// 迁移配置
        /// JSON格式存储迁移参数
        /// </summary>
        [Column(TypeName = "text")]
        public string? MigrationConfig { get; set; }

        /// <summary>
        /// 错误日志
        /// </summary>
        [Column(TypeName = "text")]
        public string? ErrorLog { get; set; }

        /// <summary>
        /// 操作用户ID
        /// </summary>
        public long? OperatorUserId { get; set; }

        /// <summary>
        /// 迁移描述
        /// </summary>
        [StringLength(1000)]
        public string? Description { get; set; }

        /// <summary>
        /// 数据一致性验证状态
        /// </summary>
        public bool IsValidated { get; set; } = false;

        /// <summary>
        /// 验证完成时间
        /// </summary>
        public DateTime? ValidatedAt { get; set; }

        /// <summary>
        /// 验证结果摘要
        /// </summary>
        [StringLength(500)]
        public string? ValidationResults { get; set; }

        /// <summary>
        /// 传输的数据量（字节）
        /// </summary>
        public long? TransferredBytes { get; set; }

        /// <summary>
        /// 传输速度（MB/s）
        /// </summary>
        public decimal? TransferSpeedMBps { get; set; }

        /// <summary>
        /// 是否支持回滚
        /// </summary>
        public bool IsRollbackable { get; set; } = false;

        /// <summary>
        /// 回滚截止时间
        /// </summary>
        public DateTime? RollbackDeadline { get; set; }

        /// <summary>
        /// 回滚备份路径
        /// </summary>
        [StringLength(500)]
        public string? RollbackBackupPath { get; set; }

        /// <summary>
        /// 迁移优先级
        /// 1-5，1为最高优先级
        /// </summary>
        public int Priority { get; set; } = 3;

        // 计算属性

        /// <summary>
        /// 进度百分比
        /// </summary>
        [NotMapped]
        public decimal ProgressPercentage => TotalRecords > 0 ? 
            Math.Round((decimal)ProcessedRecords / TotalRecords * 100, 2) : 0;

        /// <summary>
        /// 成功率
        /// </summary>
        [NotMapped]
        public decimal SuccessRate => ProcessedRecords > 0 ? 
            Math.Round((decimal)(ProcessedRecords - FailedRecords) / ProcessedRecords * 100, 2) : 0;

        /// <summary>
        /// 迁移耗时（分钟）
        /// </summary>
        [NotMapped]
        public int? DurationMinutes => CompletedAt.HasValue ? 
            (int?)Math.Round((CompletedAt.Value - StartedAt).TotalMinutes) : null;

        /// <summary>
        /// 传输数据量（MB）
        /// </summary>
        [NotMapped]
        public decimal? TransferredMB => TransferredBytes.HasValue ? 
            Math.Round((decimal)TransferredBytes.Value / (1024 * 1024), 2) : null;

        /// <summary>
        /// 是否可以回滚（基于时间检查）
        /// </summary>
        [NotMapped]
        public bool CanRollback => IsRollbackable && RollbackDeadline.HasValue && 
            DateTime.UtcNow <= RollbackDeadline.Value;
    }

    /// <summary>
    /// 租户数据清理实体
    /// 用于管理租户数据的清理和删除操作
    /// </summary>
    [Table("tenant_data_cleanups")]
    public class TenantDataCleanup : ITenantEntity
    {
        /// <summary>
        /// 主键ID
        /// </summary>
        [Key]
        public long Id { get; set; }

        /// <summary>
        /// 租户ID
        /// </summary>
        [Required]
        [StringLength(50)]
        public string TenantId { get; set; } = string.Empty;

        /// <summary>
        /// 清理名称
        /// </summary>
        [Required]
        [StringLength(200)]
        public string CleanupName { get; set; } = string.Empty;

        /// <summary>
        /// 清理类型
        /// 如：expired_data, inactive_users, old_logs, temp_files
        /// </summary>
        [Required]
        [StringLength(50)]
        public string CleanupType { get; set; } = string.Empty;

        /// <summary>
        /// 清理状态
        /// 如：pending, running, completed, failed
        /// </summary>
        [Required]
        [StringLength(50)]
        public string Status { get; set; } = "pending";

        /// <summary>
        /// 删除的记录数
        /// </summary>
        public long DeletedRecords { get; set; }

        /// <summary>
        /// 释放的存储空间（字节）
        /// </summary>
        public long FreedSpaceBytes { get; set; }

        /// <summary>
        /// 清理规则
        /// JSON格式存储清理条件
        /// </summary>
        [Column(TypeName = "text")]
        public string? CleanupRules { get; set; }

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartedAt { get; set; } = DateTime.UtcNow;

        /// <summary>
        /// 完成时间
        /// </summary>
        public DateTime? CompletedAt { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        [Column(TypeName = "text")]
        public string? ErrorMessage { get; set; }

        /// <summary>
        /// 操作用户ID
        /// </summary>
        public long? OperatorUserId { get; set; }

        /// <summary>
        /// 清理描述
        /// </summary>
        [StringLength(1000)]
        public string? Description { get; set; }

        /// <summary>
        /// 是否为试运行
        /// </summary>
        public bool IsDryRun { get; set; } = false;

        /// <summary>
        /// 需要批准的用户角色
        /// </summary>
        [StringLength(100)]
        public string? ApprovalRequiredRole { get; set; }

        /// <summary>
        /// 批准时间
        /// </summary>
        public DateTime? ApprovedAt { get; set; }

        /// <summary>
        /// 批准用户ID
        /// </summary>
        public long? ApprovalUserId { get; set; }

        /// <summary>
        /// 预定执行时间
        /// </summary>
        public DateTime? ScheduledAt { get; set; }

        /// <summary>
        /// 关联调度任务ID
        /// </summary>
        [StringLength(100)]
        public string? ScheduleId { get; set; }

        /// <summary>
        /// 受影响的表
        /// JSON数组格式存储表名列表
        /// </summary>
        [Column(TypeName = "text")]
        public string? AffectedTables { get; set; }

        /// <summary>
        /// 数据保留截止时间
        /// 超过此时间的数据将被清理
        /// </summary>
        public DateTime? DataRetentionUntil { get; set; }

        /// <summary>
        /// 是否可恢复
        /// </summary>
        public bool IsRecoverable { get; set; } = false;

        /// <summary>
        /// 恢复截止时间
        /// </summary>
        public DateTime? RecoveryDeadline { get; set; }

        /// <summary>
        /// 恢复数据路径
        /// </summary>
        [StringLength(500)]
        public string? RecoveryPath { get; set; }

        /// <summary>
        /// 清理风险级别
        /// 如：low, medium, high, critical
        /// </summary>
        [StringLength(20)]
        public string RiskLevel { get; set; } = "medium";

        /// <summary>
        /// 预估清理记录数
        /// </summary>
        public long? EstimatedRecords { get; set; }

        // 计算属性

        /// <summary>
        /// 清理耗时（分钟）
        /// </summary>
        [NotMapped]
        public int? DurationMinutes => CompletedAt.HasValue ? 
            (int?)Math.Round((CompletedAt.Value - StartedAt).TotalMinutes) : null;

        /// <summary>
        /// 释放的存储空间（MB）
        /// </summary>
        [NotMapped]
        public decimal FreedSpaceMB => Math.Round((decimal)FreedSpaceBytes / (1024 * 1024), 2);

        /// <summary>
        /// 是否需要批准
        /// </summary>
        [NotMapped]
        public bool RequiresApproval => !string.IsNullOrEmpty(ApprovalRequiredRole);

        /// <summary>
        /// 是否已批准
        /// </summary>
        [NotMapped]
        public bool IsApproved => ApprovedAt.HasValue && ApprovalUserId.HasValue;

        /// <summary>
        /// 是否可以恢复（基于时间检查）
        /// </summary>
        [NotMapped]
        public bool CanRecover => IsRecoverable && RecoveryDeadline.HasValue && 
            DateTime.UtcNow <= RecoveryDeadline.Value;

        /// <summary>
        /// 清理效率（实际删除记录数 vs 预估记录数）
        /// </summary>
        [NotMapped]
        public decimal? CleanupEfficiency => EstimatedRecords > 0 ? 
            Math.Round((decimal)DeletedRecords / EstimatedRecords.Value * 100, 2) : null;

        /// <summary>
        /// 是否为高风险清理
        /// </summary>
        [NotMapped]
        public bool IsHighRisk => RiskLevel == "high" || RiskLevel == "critical";
    }
}
